package com.mxpio.erp.plan.policy.impl;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.jpa.model.NoticeLine;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.order.policy.AbstractBizOrderPolicy;
import com.mxpio.erp.common.order.policy.OrderContext;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.common.plan.entity.*;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.vo.NoticeClassVo;
import com.mxpio.erp.common.vo.OrderExcuteLineVo;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织需求 不良品退料 执行policy
 * @author mxpio
 *
 */
public class DefectiveRejPolicy extends AbstractBizOrderPolicy {
	private List<OrderExcuteLineVo> orderExcuteVos;
	private OrderLineService orderLineService;

	public DefectiveRejPolicy(List<OrderExcuteLineVo> orderExcuteVos, OrderLineService orderLineService) {
		this.orderExcuteVos = orderExcuteVos;
		this.orderLineService = orderLineService;
	}
	@Override
	public void execute(OrderContext context) {
	}

	@Override
	public OrderContext config(OrderContext context) {
		context.setOrderExcuteVos(orderExcuteVos);
		context.setNoticeClass(ODDefectiveRejNotice.class);
		context.setPickingType(NoticeStatusEnums.NoticeType.DO_DP.getCode());
		context.setAccessType(OrderEnums.AccessType.IN.getCode());
		return context;
	}

	@Override
	public boolean beforeExecute(OrderContext context) {
		Order order = context.getEntity();
		if (order instanceof OrganizationDemand && context.getOrderExcuteVos().size()>0){
			List<OrderExcuteLineVo> orderExcuteVos = context.getOrderExcuteVos();
			List<String> orderlinesStr = orderExcuteVos.stream().map(OrderExcuteLineVo::getBizOrderlineNo).collect(Collectors.toList());
			List<OrganizationDemandLine> orderLines = JpaUtil.linq(OrganizationDemandLine.class).equal("bizNo", order.getBizNo()).in("lineNo", orderlinesStr).list();
			NoticeClassVo oDReceivingNoticeClazz = new NoticeClassVo(ODReceivingNotice.class, ODReceivingNoticeLine.class);
			NoticeClassVo oDRejectNotice = new NoticeClassVo(ODRejectNotice.class, ODRejectNoticeLine.class);
			NoticeClassVo oDSupplementNotice = new NoticeClassVo(ODSupplementNotice.class, ODSupplementNoticeLine.class);
			NoticeClassVo oDDefectiveRejNotice = new NoticeClassVo(ODDefectiveRejNotice.class, ODDefectiveRejNoticeLine.class);
			List<NoticeClassVo> noticeClassVos = new ArrayList<>();
			noticeClassVos.add(oDReceivingNoticeClazz);
			noticeClassVos.add(oDRejectNotice);
			noticeClassVos.add(oDSupplementNotice);//退料时考虑补料部分
			noticeClassVos.add(oDDefectiveRejNotice);
			orderLineService.handleBizOrderLineQuantity(orderLines, noticeClassVos, OrderEnums.AccessType.OUT.getCode());
			Map<String, OrganizationDemandLine> orderLineMap = JpaUtil.index(orderLines,"lineNo");
			for(OrderExcuteLineVo orderExcuteVo : orderExcuteVos) {
				// BigDecimal lineQuantity = orderExcuteVo.getLineQuantity();
				BigDecimal quantity = orderExcuteVo.getQuantity();
				String bizOrderlineNo = orderExcuteVo.getBizOrderlineNo();
				OrganizationDemandLine orderLine = orderLineMap.get(bizOrderlineNo);
				if (orderLine!=null){
					BigDecimal actualQuantity = orderLine.getActualQuantity();
					BigDecimal actualRejectQuantity = orderLine.getActualRejectQuantity();
					//BigDecimal planQuantity = orderLine.getPlanQuantity();
					BigDecimal planRejectQuantity = orderLine.getPlanRejectQuantity();
					//退货时，最大可退数量=已执行数量减去已执行退货数量减去计划退货数量，不考虑计划执行数量
					BigDecimal lastMax = actualQuantity.subtract(actualRejectQuantity).subtract(planRejectQuantity);
					//原执行行总数量 减去
					if (quantity.compareTo(lastMax)>0){
						context.addError("提交数据中行号【"+bizOrderlineNo+"】执行数量大于最大可执行数量【"+lastMax+"】。");
						return false;
					}
				}
			}
		}
		return true;
	}

	@Override
	public void afterExecute(OrderContext context) {

	}
	@Override
	public void apply(OrderContext context) {
		if(beforeExecute(context)) {
			execute(context);
			OrganizationDemand order = (OrganizationDemand) context.getEntity();
			List<OrderExcuteLineVo> orderExcuteVos = context.getOrderExcuteVos();
			// 遍历执行行 生成通知单
			Map<String, ODDefectiveRejNotice> noticeMap = new HashMap<>();
			Map<String,List<OrderExcuteLineVo>> voMap = new HashMap<>();

			//补料通知单
			Map<String, Notice> noticeAddMap = new HashMap<>();
			Map<String,List<OrderExcuteLineVo>> voAddMap = new HashMap<>();

			for(OrderExcuteLineVo orderExcuteVo : orderExcuteVos) {
				ODDefectiveRejNotice notice = noticeMap.get(orderExcuteVo.getWhCode());
				if(notice == null) {
					notice = new ODDefectiveRejNotice();
					//关联组织需求业务字段
					/*notice.setProductItemCode(order.getProductItemCode());
					notice.setProductItemName(order.getProductItemName());
					notice.setOrderQuantity(order.getOrderQuantity());
					notice.setProductDrawingNo(order.getProductDrawingNo());
					notice.setMainWorkshop(order.getMainWorkshop());*/

					notice.setBizOrderNo(order.getBizNo());
					notice.setNoticeDate(new Date());
					notice.setWhCode(orderExcuteVo.getWhCode());
					notice.setAccessType("in");//入库
					notice.setPickingType(context.getPickingType());
					notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CREATE.getStatusCode());
					noticeMap.put(orderExcuteVo.getWhCode(), notice);
					voMap.put(orderExcuteVo.getWhCode(), new ArrayList<OrderExcuteLineVo>());
				}
				voMap.get(orderExcuteVo.getWhCode()).add(orderExcuteVo);
			}
			// 生成通知单明细
			for(Map.Entry<String,ODDefectiveRejNotice> entry : noticeMap.entrySet()) {
				Notice notice = entry.getValue();
				JpaUtil.save(notice);
				int lineNo = 0;
				for(OrderExcuteLineVo vo : voMap.get(entry.getKey())) {
					lineNo++;
					NoticeLine line = notice.createLine(vo);
					line.setLineNo(lineNo+"");
					Item item = JpaUtil.linq(Item.class).idEqual(vo.getItemCode()).findOne();
					line.setItemName(item.getItemName());
					line.setItemSpec(item.getItemSpec());
					line.setUnitCode(item.getUnitCode());
					line.setDrawingNo(item.getDrawingNo());
					JpaUtil.save(line);
				}
			}

			if(OrderStatusEnums.OrderStatus.PLAN.getStatusCode().equals(order.getOrderStatus())||
					OrderStatusEnums.OrderStatus.ORDERED.getStatusCode().equals(order.getOrderStatus())){
				order.setOrderStatus(OrderStatusEnums.OrderStatus.PROCESSING.getStatusCode());
				order.setExecuteTime(new Date());
				order.setExecutor(SecurityUtils.getLoginUsername());
				JpaUtil.update(order);
			}
			afterExecute(context);
		} else {
			if(CollectionUtils.isEmpty(context.getErrors())) {
				context.addError("前置校验不通过");
			}
		}
	}

}
